//
//  YPWmcManager+Api.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/6/7.
//

import RxRelay
import UIKit
import YPBedrock

// MARK: - 开放枚举以及别名区

public extension YPWmcManager {
    /// 水印照片结果
    typealias PhotoResult = (
        watermarkPhoto: UIImage,
        standardPhoto: UIImage,
        watermarkModel: WmcWatermarkDetailModel,
        qrcodePhoto: UIImage?
    )

    /// 水印视频结果
    typealias VideoResult = (
        videoUrl: URL,
        videoPath: String,
        videoCover: UIImage,
        videoCoverPath: String,
        videoTime: Double,
        watermarkModel: WmcWatermarkDetailModel
    )

    /// 网络环境
    enum EnvironmentType: Int {
        /// 开发环境
        case develop
        /// 测试环境
        case test
        /// 预发布环境
        case pre_release
        /// 正式环境
        case release
        
        /// 微信公众号appId
        var wechatAppId: String {
            switch self {
            case .release, .pre_release:
                return "wx3f9ac8f4608b6afa"
            case .test, .develop:
                return "wx33cdaf603824341c"
            }
        }
        
        /// web页面base url
        var baseWebURL: String {
            let host = "https://cdn.cdypkj.cn"
            let path: String
            switch self {
            case .develop, .test:
                path = "h5-dev"
            case .pre_release:
                path = "h5-pre"
            case .release:
                path = "h5"
            }
            let url = "\(host)/\(path)"
            return url
        }
        
        /// 拼图意见反馈 configId
        var feedbackConfigId: Int {
            switch self {
            case .develop, .test:
                return 31
            case .pre_release, .release:
                return 30
            }
        }
    }

    /// 宿主平台
    enum Platform: Int {
        /// 水印相机
        case watermarkCamera
        /// 鱼泡网
        case fishBubble
        /// 记工记账
        case recordWork
        /// 工程协同
        case saas
    }
    
    /// 水印组类型
    enum WatermarkGroupType {
        /// 默认水印组，既水印相机的所有水印
        case `default`

        /// 安心记
        case restAssuredRecord

        /// 自定义组，既自选择要哪些水印
        case custom(classifyIds: [Int] = [], templateTypes: [WmcWatermarkDetailModel.TemplateType])
    }

    /// AI识别水印组类型
    enum RecognitionWatermarkGroupType {
        /// 默认水印组，既水印相机的所有水印
        case `default`
        
        /// 自定义组，既自选择要哪些水印
        case custom(classifyIds: [Int] = [], templateTypes: [Int])
    }

    /// 活动类型
    enum ActivityType: CaseIterable {
        // ps: 考虑到后头可能会有其他平台接入类似功能，所以加平台前缀

        /// 鱼泡送积分
        case yp_giveIntegral
    }
}

// MARK: - 全局接口Header头设置

public extension YPWmcManager {
    /// 鱼泡接口请求头扩展字段
    static func setYuPaoExtensionHeaders(_ headers: [String: String]) {
        shared.yupaoEextensionHeaders = headers
    }

    /// 多媒体接口请求头扩展字段
    static func setMediaExtensionHeaders(_ headers: [String: String]) {
        shared.mediaExtensionHeaders = headers
    }

    /// 原php接口请求头扩展字段
    static func setOriginExtensionHeaders(_ headers: [String: String]) {
        shared.originExtensionHeaders = headers
    }
}

// MARK: - 全局临时附加值功能

public extension YPWmcManager {
    /// 存入一个临时附加对象
    /// 该值以Entry为键值，确保各个业务层互不干扰
    /// 该值在水印相机页面Dismiss之后会自动清空
    static func saveAttached(_ value: Any, entry: Int) {
        shared.attachedMap[entry] = value
    }

    /// 获取一个附加对象
    /// 该值以Entry为键值，确保各个业务层互不干扰
    /// 该值在水印相机页面Dismiss之后会自动清空
    static func getAttached<T>(entry: Int) -> T? {
        if let value = shared.attachedMap[entry] as? T {
            return value
        }
        return nil
    }

    /// 移除附加对象
    /// 该值以Entry为键值，确保各个业务层互不干扰
    /// 该值在水印相机页面Dismiss之后会自动清空
    static func removeAttached(entry: Int) {
        shared.attachedMap.removeValue(forKey: entry)
    }
}

// MARK: - 页面使用功能

public extension YPWmcManager {
    /// 拉起水印相机
    /// - Parameters:
    ///   - appid: 业务平台，鱼泡、记工记账、协同等
    ///   - entry: 业务入口值，确保各个业务层互不干扰
    ///   - watermarkGroupType: 水印组类型
    ///   - animated: 动画效果
    ///   - presentCompletion: 动画完成回调
    ///   - dismissEventBlock: 执行dismiss事件回调
    static func presentCamera(appId: String = "101",
                              entry: Int,
                              watermarkGroupType: WatermarkGroupType = .default,
                              recognitionWatermarkGroupType: RecognitionWatermarkGroupType = .default,
                              animated: Bool = true,
                              presentCompletion: YPBlock.Empty? = nil,
                              dismissEventBlock: YPBlock.Empty? = nil)
    {
        shared.appId = appId
        shared.entry = entry
        shared.watermarkGroupType = watermarkGroupType
        shared.recognitionWatermarkGroupType = recognitionWatermarkGroupType
        shared.dismissEventBlock = dismissEventBlock
        let vm = WmcHomeVM()
        let homeVC = WmcHomeVC(vm)
        present(vc: homeVC, animated: animated, presentCompletion: presentCompletion)
    }

    /// 拉起个人云相册
    /// - Parameters:
    ///   - animated: 动画效果
    ///   - presentCompletion: 动画完成回调
    static func PresentPersonalCloudAlbum(animated: Bool = true,
                                          presentCompletion: YPBlock.Empty? = nil)
    {
        var vm = WmcPersonCloudAlbumTabBarVM()
        vm.isBackToDismiss = true
        let vc = WmcPersonCloudAlbumTabBarVC(vm)
        vc.teamAblum = vm.teamAblum
        present(vc: vc, animated: animated, settingPresentVC: false, presentCompletion: presentCompletion)
    }

    /// 拉起媒体浏览器
    /// - Parameters:
    ///   - title: 标题
    ///   - mediaList: 媒体列表
    ///   - showIndex: 显示第几个索引
    ///   - tag: 标签，用于代理区分
    ///   - animated: 动画效果
    ///   - presentCompletion: 动画完成回调
    static func presentMediaBrowse(
        topLeftStyle: WmcMediaBrowseVM.TopLeftStyle = .close,
        topRightStyle: WmcMediaBrowseVM.TopRightStyle = .none,
        mediaList: [WmcMedia],
        showIndex: Int = 0,
        tag: String = "",
        animated: Bool = true,
        presentCompletion: YPBlock.Empty? = nil
    ) {
        let browseVM = WmcMediaBrowseVM()
        browseVM.topLeftStyle = topLeftStyle
        browseVM.topRightStyle = topRightStyle
        browseVM.albumType = .custom(tag: tag)
        browseVM.mediaList = mediaList
        browseVM.showIndex = showIndex
        let mediaBrowseVC = WmcMediaBrowseVC(browseVM)
        present(vc: mediaBrowseVC, animated: animated, presentCompletion: presentCompletion)
    }

    /// 推出自定义页面
    ///
    ///     调用该方法是必须是在拉起水印相机页面的情况下才能生效，否则将无效
    /// - Parameter view: 自定义视图
    static func pushCustom(view: WmcCustomViewProtocol) {
        guard let navVC = shared.presentVC as? WmcNavVC else { return }
        let customVC = WmcCustomVC(customView: view)
        let style = view.pushTransitionStyle(.current)
        let animated = view.pushTransitionAnimated(.current)
        navVC.wmc_push(vc: customVC, style: style, animated: animated)
    }

    /// 使用路由推出内置VC
    ///
    ///         目前只支持：媒体浏览器、网页
    /// - Parameters:
    ///   - navigationKey: 路由键值
    ///   - style: 推出样式
    ///   - viewModel: 视图模型
    ///   - animated: 动画
    /// - Returns: 控制器
    @discardableResult
    static func pushNavigation(
        _ navigationKey: WmcNavigatorManager.Path,
        style: WmcTransition.Style? = nil,
        viewModel: WmcBaseVM? = nil,
        animated: Bool = true,
        completion: YPBlock.Empty? = nil
    )
        -> UIViewController?
    {
        WmcNavigatorManager.push(
            navigationKey,
            style: style,
            parms: viewModel,
            animated: animated,
            completion: completion
        )
    }

    /// 从水印相机的任意页面退出
    /// - Parameters:
    ///  - animated: 动画
    ///  - completion: 完成回调
    static func dismiss(animated: Bool = true,
                        completion: YPBlock.Empty? = nil)
    {
        guard let navVC = YPApp.CurrentVC?.navigationController as? WmcNavVC else { return }
        var isHome = false
        // 操作相关VC停止该停止的
        for vc in navVC.viewControllers {
            if let homeVC = vc as? WmcHomeVC {
                isHome = true
                // 停止相机活动
                homeVC.stopCamera()
                // 停止闪光灯
                homeVC.setFlashMode(.off)
                // 释放相机
                homeVC.cameraView = nil
                // 停止其他管理器
                WmcMotionManager.shared.stop() // 运动传感器
                // 停止真实数据监听管理器
                WmcDateManager.shared.stopDate()
                WmcLocationManager.stopLocation()
//                WmcLocationManager.stopAutomaticSearchPoi()
                WmcCLLocationManager.shared.stopUpdatingHeading()
                WmcDecibeManager.shared.stop()

                // 通知回调消失
                shared.dismissEventBlock?()
            } else {}
        }
        // 退出页面
        navVC.dismiss(animated: animated, completion: {
            completion?()
            if isHome {
                // 释放回调
                shared.dismissEventBlock = nil
                // 释放推出的页面
                shared.presentVC = nil
                // 解除UI代理行为
                shared.uiDelegate.releaseDelegate()
                // 解除代理行为
                shared.delegate.releaseDelegate()
                // 清除全局附加数据
                clearAttached()
            }
        })
    }
}

extension YPWmcManager.EnvironmentType {
    /// 意见返回 h5 环境变量
    var feedBackH5_url: String {
        switch self {
        case .develop:
            return "https://h5hybridtest.yupaowang.com"
        case .test:
            return "https://h5hybridtest.yupaowang.com"
        case .pre_release:
            return "https://h5hybridmaster.yupaowang.com"
        case .release:
            return "https://h5hybridprod.yupaowang.com"
        }
    }
}
